package com.jinbooks.web.merchant.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jinbooks.authn.annotation.CurrentUser;
import com.jinbooks.entity.Message;
import com.jinbooks.entity.dto.ListIdsDto;
import com.jinbooks.entity.idm.UserInfo;
import com.jinbooks.entity.merchant.MerchantProduct;
import com.jinbooks.entity.merchant.dto.MerchantProductPageDto;
import com.jinbooks.persistence.service.MerchantProductService;
import com.jinbooks.validate.AddGroup;
import com.jinbooks.validate.EditGroup;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 商户产品控制器
 *
 * @author lingma
 */
@RestController
@RequestMapping("/merchant/product")
@RequiredArgsConstructor
@Slf4j
public class MerchantProductController {

    private final MerchantProductService merchantProductService;

    /**
     * 分页查询商户产品列表
     */
    @GetMapping("/fetch")
    public Message<Page<MerchantProduct>> fetch(@ParameterObject MerchantProductPageDto dto, @CurrentUser UserInfo currentUser) {
        dto.setWorkspaceId(currentUser.getWorkspaceId());
        log.debug("fetch {}", dto);
        return Message.ok(merchantProductService.pageList(dto));
    }

    /**
     * 获取商户产品详情
     */
    @GetMapping("/{id}")
    public Message<MerchantProduct> get(@PathVariable("id") String id) {
        log.debug("get {}", id);
        return new Message<>(Message.SUCCESS, merchantProductService.getById(id));
    }

    /**
     * 新增商户产品
     */
    @PostMapping
    public Message<Boolean> save(@Validated(AddGroup.class) @RequestBody MerchantProduct dto, @CurrentUser UserInfo currentUser) {
        dto.setWorkspaceId(currentUser.getWorkspaceId());
        log.debug("save {}", dto);
        return Message.ok(merchantProductService.save(dto));
    }

    /**
     * 更新商户产品
     */
    @PutMapping
    public Message<Boolean> update(@Validated(EditGroup.class) @RequestBody MerchantProduct dto, @CurrentUser UserInfo currentUser) {
        dto.setWorkspaceId(currentUser.getWorkspaceId());
        log.debug("update {}", dto);
        return Message.ok(merchantProductService.update(dto));
    }

    /**
     * 删除商户产品
     */
    @DeleteMapping("/batch")
    public Message<Boolean> delete(@Validated @RequestBody ListIdsDto dto, @CurrentUser UserInfo currentUser) {
        dto.setWorkspaceId(currentUser.getWorkspaceId());
        log.debug("delete {}", dto);
        return Message.ok(merchantProductService.deleteByIds(dto.getListIds()));
    }
}